// pages/BrowsingHistory/BrowsingHistory.js
import {
    queryUserBrowseHistory,
    queryCountOfUserBrowseHistory,
    deleteAllBrowseHistory,
    deleteBrowseHistoryByIds
} from "../../service/history"
import request from "../../service/request"
import Toast from '@vant/weapp/toast/toast';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 修改状态 0-管理 1-完成
        modifyStatus: 0,
        // 是否全选
        selectAll: false,
        // 浏览记录列表
        browseHistoryList: [],
        // 需要被删除的productId集合
        pendingDeleteProductSet: {},
        // 浏览记录的数量,
        count: -1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        const res = await request.all(queryUserBrowseHistory(), queryCountOfUserBrowseHistory())
        this.setData({
            browseHistoryList: res[0].data,
            count: res[1].data,
        })
        console.log(this.data.browseHistoryList);
        this.data.pendingDeleteProductSet = new Set()
    },
    /**
     * 点击管理选项
     */
    onTapModify() {
        this.setData({
            modifyStatus: this.data.modifyStatus === 0 ? 1 : 0
        })
        if (this.data.modifyStatus === 0) {
            this.setData({
                selectAll: false
            })
        }
    },
    /**
     * 点击全选按钮
     */
    onTapSelectAll(event) {
        this.setData({
            selectAll: event.detail
        })
    },


    /**
     * 触发商品id添加事件
     */
    onTriggerAdd(event) {
        this.data.pendingDeleteProductSet.add(event.detail.productId)
        if (this.data.pendingDeleteProductSet.size === this.data.count) {
            this.setData({
                selectAll: true
            })
        }
    },
    /**
     * 触发商品id删除事件
     */
    onTriggerRemove(event) {
        this.data.pendingDeleteProductSet.delete(event.detail.productId)
        this.setData({
            selectAll: false
        })
    },
    // 点击删除按钮
    async onTapDeleteButton() {
        if (this.data.selectAll) {
            await deleteAllBrowseHistory()
            Toast({
                message: "删除成功",
                duration: 500
            });
        } else {
            await deleteBrowseHistoryByIds(Array.from(this.data.pendingDeleteProductSet))
            Toast({
                message: "删除成功",
                duration: 500
            });
        }
        await this.onLoad()
    }

})